<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class CategoryController extends Controller
{
    // 中间键 判断是否登录
    public function __construct()
    {
        $this -> middleware('login');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        $num = $request -> input('num', 5);
        $keywords = $request -> input('keywords','');
        // dd($userData);
        $data = DB::table('category as c1')
            -> select('c1.*', 'c2.catname as pname', DB::raw("concat(c1.path,',',c1.id) as sortpath"))
            -> leftJoin('category as c2', 'c1.pid', '=', 'c2.id')
            -> where('c1.catname', 'like', '%'.$keywords.'%')
            -> orderBy('sortpath')
            -> paginate($num);
        // dd($data);

        // 遍历查询出来的
        foreach ($data as $key => $value) {
            $num = substr_count($value -> path, ',');
            $str = str_repeat('|----', $num);
            $data[$key] -> catname = $str.$value -> catname;
        }
        return view('admin.category.index', ['data' => $data, 'request' => $request -> all(), 'title' => '分类列表']);
    }

    /**
     * Show the form for creating a new resource.
     * 添加文章 add模板
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = DB::table('category')
             -> select('category.*', DB::raw("concat(category.path,',',category.id) as sortpath"))
             -> orderBy('sortpath')
             -> get();
        foreach ($data as $key => $value) {
            $num = substr_count($value -> path,',');
            $str = str_repeat('|----', $num);
            $data[$key] -> catname = $str.$value -> catname;
        }
        // dd($data);
        return view('admin.category.add', ['title' => '添加分类', 'data' => $data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $data = $request -> except('_token');
        // dd($data);
        // 判断是否添加跟分类
        if($data['pid'] == '0')
        {
            // dd($data);
            $data['path'] = $data['pid'];
            $time = date('Y-m-d H:i:s');
            $data['created_at'] = $time;
            $data['updated_at'] = $time;
            $res = DB::table('category') -> insert($data);
            if($res)
            {
                return redirect('/Admin/category') -> with(['info' => '添加成功']);
            }else
            {
                return back() -> with(['info' => '添加失败']);
            }
        }
        // 获取父path
        $parent_path = DB::table('category') -> where('id', $data['pid']) -> first() -> path;
        // dd($parent_path);
        // 拼自己的path
        $self_path = $parent_path.','.$data['pid'];
        // 放到数组中
        $data['path'] = $self_path;
        $time = date('Y-m-d H:i:s');
        $data['created_at'] = $time;
        $data['updated_at'] = $time;
        // dd($data);

        $res = DB::table('category') -> insert($data);

        if($res)
        {
            return redirect('/Admin/category') -> with(['info' => '添加成功']);
        }else
        {
            return back() -> with(['info' => '添加失败']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // 查找数据库 查看详情
        $data = DB::table('categoryinfo') -> where('aid', $id) -> get();
        // dd($data);
        return view('admin.category.show', ['title' => '分类详情', 'data' => $data]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        // dd($id);
        $data = DB::table('category')
             -> select('category.*', DB::raw("concat(category.path,',',category.id) as sortpath"))
             -> orderBy('sortpath')
             -> get();
        // 当前的
        $cateData = DB::table('category') -> where('id',$id) -> first();
        foreach ($data as $key => $value) {
            $num = substr_count($value -> path,',');
            $str = str_repeat('|----', $num);
            $data[$key] -> catname = $str.$value -> catname;
        }
        // dd($data);
        return view('admin.category.edit', ['title' => '分类编辑', 'data' => $data, 'cateData' => $cateData]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
         $data = $request -> except('_token','_method');
        // dd($data);
        // 获取父path
        $parent_path = DB::table('category') -> where('id', $data['pid']) -> first() -> path;
        // dd($parent_path);
        // 拼自己的path
        $self_path = $parent_path.','.$data['pid'];
        // 放到数组中
        $data['path'] = $self_path;
        $time = date('Y-m-d H:i:s');
        $data['updated_at'] = $time;
        // dd($data);

        $res = DB::table('category') -> where('id',$data['pid']) -> update($data);

        if($res)
        {
            return redirect('/Admin/category') -> with(['info' => '更新成功']);
        }else
        {
            return back() -> with(['info' => '更新失败']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 判断有没有子分类,如果有,就不删除
        $res = DB::table('category') -> where('pid', $id) -> first();
        if($res)
        {
            return back() -> with(['info' => '有子分类,不能够删除']);
        }
        // 如果没有分类 就给删除
        $res = DB::table('category') -> where('id', $id) -> delete();
        if($res)
        {
            return redirect('/Admin/category') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }
}
